package com.jdy.haoduoai.service;

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;

import com.jdy.haoduoai.util.LeXiaoXiaoBanLog;

/**
 * CountDownService.
 * 
 * @author zp @ 2015-6-11 下午3:53:25
 */
public class CountDownService extends Service {

  private final static String TAG = "CountDownService";

  public static final String COUNTDOWN_BR = "com.jdy.haoduoai.service.countdown_br";

  public static final String TOTAL_MILLIS = "total_millis";

  public static final String REMAINNING_SECONDS = "remainning_seconds";

  public static final String VELOCITY = "velocity";

  public static final String INITIAL_POSITION = "initial_pos";

  Intent remainingSecondsIntent = new Intent(COUNTDOWN_BR);

  CountDownTimer cdt = null;

  private long mTotalMillis;

  private float mReservedVelocity;

  private float mReservedInitialPos;

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public void onDestroy() {

    cdt.cancel();
    LeXiaoXiaoBanLog.i(TAG, "Timer cancelled");
    super.onDestroy();
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    this.mTotalMillis = intent.getLongExtra(TOTAL_MILLIS, 30000);

    this.mReservedVelocity = intent.getFloatExtra(VELOCITY, 0);

    this.mReservedInitialPos = intent.getFloatExtra(INITIAL_POSITION, 0);

    startCountDown();

    return START_STICKY;
  }

  private void startCountDown() {
    LeXiaoXiaoBanLog.i(TAG, "Starting timer...");
    cdt = new CountDownTimer(mTotalMillis, 1000) {
      @Override
      public void onTick(long millisUntilFinished) {

        LeXiaoXiaoBanLog.i(TAG, "Countdown seconds remaining: "
            + millisUntilFinished / 1000);
        remainingSecondsIntent.putExtra(TOTAL_MILLIS, mTotalMillis / 1000);
        remainingSecondsIntent.putExtra(REMAINNING_SECONDS,
            millisUntilFinished / 1000);
        remainingSecondsIntent.putExtra(VELOCITY, mReservedVelocity);
        remainingSecondsIntent.putExtra(INITIAL_POSITION, mReservedInitialPos);

        sendBroadcast(remainingSecondsIntent);
      }

      @Override
      public void onFinish() {
        LeXiaoXiaoBanLog.i(TAG, "Timer finished");
        stopSelf();
      }
    };

    cdt.start();
  }

  @Override
  public IBinder onBind(Intent arg0) {
    return null;
  }
}
